package sy.util;

import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class EMailUtil {
	private static Properties prop = new Properties();
	public static Map<String, String> tjrPhone = new HashMap<String, String>();
	static {
		try {
		    prop.load(EMailUtil.class.getClassLoader().getResourceAsStream("mail.properties"));
		} catch(Exception e) {
			e.printStackTrace();
		}
		tjrPhone.put("陈志勇", "13908383779");
		tjrPhone.put("刘江", "13708339311");
	}

	private static Authenticator getAuthenticator() {
		// 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = prop.getProperty("mail.user");
                String password = prop.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        return authenticator;
	}
	
	public static boolean sendMail(String[] toAddresses, String subject, String content) {
		try {
			System.out.println("sending email to " + arrayToString(toAddresses));
			System.out.println("subject is " + subject);
			System.out.println("content is " + content);
			// 使用环境属性和授权信息，创建邮件会话
	        Session mailSession = Session.getInstance(prop, getAuthenticator());
	        // 创建邮件消息
	        MimeMessage message = new MimeMessage(mailSession);
	        // 设置发件人
	        InternetAddress from = new InternetAddress("office@cq666666.cn");
	        message.setFrom(from);
	        // 设置收件人
			Address[] addresses = new InternetAddress[toAddresses.length];
			for(int i = 0; i < addresses.length; i++) {
	        	Address to = new InternetAddress(toAddresses[i]);
				addresses[i] = to;
			}
	        message.setRecipients(RecipientType.TO, addresses);
	        // 设置邮件标题
	        message.setSubject(subject);
	        // 设置邮件的内容体
	        message.setContent(content, "text/html;charset=UTF-8");
	        // 发送邮件
	        Transport.send(message);
	        System.out.println("email sent!");
			return true;
		} catch(Exception e) {
			System.out.println("sent failed: " + e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public static void test() {
		EMailUtil.sendMail(new String[]{"775205328@qq.com"}, "来自第六边界的邀请", "<html><body>特邀您成为我们的荣誉会员，点击以下链接激活：<a href='www.cq666666.cn'>www.cq666666.cn</a></body></html>");
	}

	private static String arrayToString(String[] array) {
		StringBuilder sb = new StringBuilder();
		for(String s : array) {
			sb.append(s + ",");
		}
		return sb.toString();
	}

	public static String[] getServicePersonE() {
		String addresses = prop.getProperty("notifyPersons");
		return addresses.split(",");
 	}

}
